package com.dz.service.impl;

import com.dz.bean.Booking;
import com.dz.mapper.BookingDao;
import com.dz.service.BookingService;
import com.dz.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class BookingServiceImpl implements BookingService {

    @Autowired
    private BookingDao bookingDao;

    @Override
    public Booking add(Booking booking) {
        // 1. 检查时间段冲突
        List<Booking> conflictingBookings = bookingDao.findBookingsInTimeRange(
                booking.getGuideId(),
                booking.getStartTime(),
                booking.getEndTime()
        );
//        if (!conflictingBookings.isEmpty()) {
//            throw new RuntimeException("该导游在所选时间段内已被预约，请选择其他时间");
//        }
        // 过滤掉自己（如果是编辑操作）
        if (!conflictingBookings.isEmpty()) {
            // 检查是否是编辑自己的预约
            boolean isEditingSelf = conflictingBookings.stream()
                    .anyMatch(b -> b.getId() != null && b.getId().equals(booking.getId()));

            // 如果不是编辑自己且存在冲突，则抛出异常
            if (!isEditingSelf) {
                throw new RuntimeException("该导游在所选时间段内已被预约，请选择其他时间");
            }
        }

        // 2. 无冲突则创建预约
        bookingDao.add(booking);
        return bookingDao.findById(booking.getId());
    }

    @Override
    public int delete(Integer id) {
        // 先查询预约信息，获取guideId
        Booking booking = bookingDao.findById(id);
        if (booking != null) {
            return bookingDao.delete(id);
        }
        return 0;
    }

    @Override
    public Booking edit(Booking booking) {
        bookingDao.edit(booking);
        Booking result = bookingDao.findById(booking.getId());
        return result;
    }

    @Override
    public List<Booking> all(Booking booking) {
        return bookingDao.all(booking);
    }

    @Override
    public int countByVisitorId(Integer visitorId) {
        return bookingDao.countByVisitorId(visitorId);
    }

    @Override
    public Booking findById(Integer id) {
        return bookingDao.findById(id);
    }


    @Override
    public void findByVisitorId(Page page, Integer visitorId) {
        int totalCount = bookingDao.countByVisitorId(visitorId);
        List<Booking> data = bookingDao.findByVisitorId(visitorId, page);
        page.setTotalCount(totalCount);
        page.setData(data);
    }

    @Override
    public int updateToPaid(Integer id) {
        return bookingDao.updateToPaid(id);
    }
}
